﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Contract.Infrastructure.Repository
{
    public class BaseRepository<T>:IRepository<T> where T : class
    {
        private readonly EfCoreDbContext _context;

        public BaseRepository(EfCoreDbContext context)
        {
            _context = context;
        }

        public async Task<IQueryable<T>> GetAllAsync()
        {
            var value = _context.Set<T>();
            var list = await value.ToListAsync();
            return list.AsQueryable();
        }

        public async Task<int> AddAsync(T t)
        {
            var value = _context.Set<T>();
            await value.AddAsync(t);
            var ind = await _context.SaveChangesAsync();
            return ind;
        }

        public async Task<int> DeleteAsync(int id)
        {
            var value = _context.Set<T>();
            var info = await value.FindAsync(id);
            value.Remove(info);
            var ind = await _context.SaveChangesAsync();
            return ind;
        }

        public async Task<int> DeleteAsync(Expression<Func<T, bool>> expression)
        {
            var value = _context.Set<T>();
            var list = await value.Where(expression).ToListAsync();
            value.RemoveRange(list);
            var ind = await _context.SaveChangesAsync();
            return ind;
        }

        public async Task<T> GetAsync(int id)
        {
            var value = _context.Set<T>();
            var info = await value.FindAsync(id);
            return info;
        }

        public async Task<T> GetAsync(Expression<Func<T, bool>> expression)
        {
            var value = _context.Set<T>();
            var info = await value.Where(expression).FirstOrDefaultAsync();
            return info;
        }

        public async Task<IQueryable<T>> GetListAsync(Expression<Func<T, bool>> expression)
        {
            var value = _context.Set<T>();
            var list = await value.Where(expression).ToListAsync();
            return list.AsQueryable();
        }

        public async Task<int> UpdateAsync(T t)
        {
            var value = _context.Set<T>();
            value.Update(t);
            var ind = await _context.SaveChangesAsync();
            return ind;
        }
    }
}
